﻿function Editor_OperationClass() {
    this.__Mode__ = "H";
    this.__Size__ = false;
    this.__Width__ = 0;
    this.__Height__ = 0;
    this.__Top__ = 0;
    this.__Left__ = 0;
    this.__Div__ = Common.Doc.Div;
    this.__Editor__ = Common.Doc.Editor;
    
    this.Init();
};
Editor_OperationClass.prototype =
{
    Init: function() {
        this.FrameDocument = Method.FD(Common.FrameName);
        this.FrameElement = Method.FE(Common.FrameName);
        this.FrameTextArea = Method.G(Common.AreaName);
        this.ParentElement = Method.FE(Method.R(Common.HTMLFrameName), "parent");
        this.ParentTextArea = Common.Doc.getElementById(Method.R(Common.HTMLAreaName));
        this.Range = this.FrameDocument;

        var base = this;
        var doc = document.documentElement;
        var divAP = Method.L(Method.G(Common.ToolBar));
        this.FrameElement.width = doc.clientWidth;
        this.FrameElement.height = doc.clientHeight - divAP.OffsetHeight;
        this.FrameTextArea.style.width = doc.clientWidth;
        this.FrameTextArea.style.height = doc.clientHeight - divAP.OffsetHeight - 2;
        // 将值返回到 TextArea 中
        this.ParentElement.onblur = function() {
            //            base.ParentTextArea.value = base.__Mode__ == "H"
            //            ? base.__Editor__.body.innerHTML
            //            : base.FrameTextArea.value;
        base.ParentTextArea.value = xHTML(base.FrameDocument.body);
        };
        var isMarkCursorPos;
        // 获取光标位置
        this.FrameElement.onbeforedeactivate = function() {
            var type = base.FrameDocument.selection.type.toLowerCase();
            var range = base.FrameDocument.selection.createRange();
            if (type != "control") {
                isMarkCursorPos = range.getBookmark();
            }
        };
        // 设置光标位置
        this.FrameElement.onactivate = function() {
            var range;
            if (isMarkCursorPos) {
                var range = base.FrameDocument.body.createTextRange();
                range.moveToBookmark(isMarkCursorPos);
                isMarkCursorPos = null;
            } else {
                range = base.Range == base.FrameDocument
                    ? base.Range.selection.createRange()
                    : base.Range;
            }
            range.select();
        };
    },
    Focus: function() {
        this.FrameDocument.body.focus();
    },
    Blur: function() {
        // 轮询操作是为了让 iframe 能加载完成文档模型，不然 body 会为 null
        var interval = setInterval(function() {
            try {
                Method.FD("ParaFrame", "parent").body.focus();
                clearInterval(interval);
            } catch (e) { };
        }, 100);
    },
    CreateRange: function() {
        this.RangeType = this.FrameDocument.selection.type.toLowerCase();
        if (this.RangeType != "none") {
            this.Range = this.FrameDocument.selection.createRange();
        } else {
            this.Range = this.FrameDocument;
        }
    },
    GetElement: function() {
        var range = this.Range, element, parentElement;
        if (this.RangeType == "text") {
            element = range.parentElement();
            parentElement = range.parentElement();
        } else if (this.RangeType == "control") {
            element = range.commonParentElement()
            parentElement = element.parentElement;
        } else {
            element = range.selection.createRange().parentElement();
            parentElement = element;
        }
        this.Element = { Parent: parentElement, Self: element };
    },
    Cmd: function(cmd, para) {
        this.Focus();
        if (para) {
            if (para == "RemoveFormat") {
                this.Range.execCommand(para);
            } else {
                this.Range.execCommand(cmd, false, para);
            }
        } else {
            this.Range.execCommand(cmd);
        }
    },
    PasteHTML: function(html) {
        this.Focus();
        var range = this.Range == this.FrameDocument
            ? this.Range.selection.createRange()
            : this.Range;
        range.pasteHTML(html);
    },
    Dialog: function(fileName) {
        var html = '', div = this.__Div__;
        html += '<iframe style="width:100%; height:100%" marginwidth="0" marginheight="0" ';
        html += 'frameborder="0" scrolling="no" allowTransparency="true" id="ParaFrame" ';
        html += 'src="Dialogs/{0}"></iframe>';

        this.CreateRange();
        this.GetElement();
        this.Blur();
        div.Create();
        div.Container.innerHTML = Method.F(html, fileName);
        div.Show();
    },
    // 文本模式
    __Source__: function() {
        Method.Display(this.FrameTextArea, "block");
        Method.Display(this.FrameElement, "none");
        this.__Mode__ = "S";
        this.FrameTextArea.focus();
        this.FrameTextArea.value = this.__Editor__.body.innerHTML;
    },
    // Html 代码模式
    __Html__: function() {
        Method.Display(this.FrameTextArea, "none");
        Method.Display(this.FrameElement, "block");
        this.__Mode__ = "H";
        this.Focus();
        this.__Editor__.body.innerHTML = this.FrameTextArea.value;
    },
    // 改变编辑模式
    ChangeMode: function() {
        var ena = [28, 29, 30, 31, 32, 33]; // 不改变状态的按钮
        var bar = Method.G(Common.ToolBar);
        var as = bar.all.tags("A");
        if (this.__Mode__ == "H") {
            this.__Source__();
            this.__Mode__ = "S";
            for (var i = 0; i < as.length; i++) {
                for (var j = 0; j < ena.length; j++) {
                    if (i + 1 == ena[j]) {
                        break;
                    } else if (j + 1 == ena.length) {
                        as[i].disabled = true;
                        as[i].style.filter = "Gray()";
                    }
                }
                if (i + 1 == 31) {
                    as[i].className = "bar_31 btnSource";
                    as[i].title = "文本模式";
                }
            }

        } else {
            this.__Html__();
            this.__Mode__ = "H";
            for (var i = 0; i < as.length; i++) {
                for (var j = 0; j < ena.length; j++) {
                    if (i + 1 == ena[j]) {
                        break;
                    } else if (j + 1 == ena.length) {
                        as[i].disabled = false;
                        as[i].style.filter = "";
                    }
                }
                if (i + 1 == 31) {
                    as[i].className = "bar_31";
                    as[i].title = "编辑器模式";
                }
            }
        }
    },
    // 最大化切换
    Size: function() {
        // 改变调用的主 iframe 的样式达到最大化的效果
        var docParent = Common.Doc.documentElement;

        if (this.__Size__) {
            this.__Size__ = false;

            docParent.style.overflow = "";
            this.ParentElement.width = this.__Width__;
            this.ParentElement.height = this.__Height__;
            this.ParentElement.style.cssText = "zIndex:9990;";
            // 移动滚动条
            parent.scrollTo(this.__Left__, this.__Top__);
        } else {
            this.__Size__ = true;
            this.__Width__ = this.ParentElement.width;
            this.__Height__ = this.ParentElement.height;
            this.__Top__ = docParent.scrollTop;
            this.__Left__ = docParent.scrollLeft;

            docParent.style.overflow = "hidden";
            this.ParentElement.width = docParent.clientWidth;
            this.ParentElement.height = docParent.clientHeight;
            this.ParentElement.style.cssText = "position:absolute;top:0;left:0;zIndex:9990;";
            // 移动滚动条
            parent.scrollTo(0, 0);
        }
        this.Init();
    },
    // 改变高度
    Height: function(symbol) {
        var pfHeight = parseInt(this.ParentElement.height);
        var fHeight = parseInt(this.FrameElement.height);
        var tHeight = parseInt(this.FrameTextArea.style.height);
        if (symbol == "-" && pfHeight <= Common.Height * 2) return;
        this.ParentElement.height = symbol == "+" ? pfHeight + Common.Height : pfHeight - Common.Height;
        this.FrameElement.height = symbol == "+" ? fHeight + Common.Height : fHeight - Common.Height;
        this.FrameTextArea.style.height = symbol == "+" ? tHeight + Common.Height : tHeight - Common.Height;
    },
    // 纯文本
    Txt: function() {
        if (confirm("将此文档转换为纯文本将会遗失某些格式。\n\n您确定要继续吗？")) {
            var range = this.FrameDocument.body.createTextRange();
            if (range) {
                this.FrameDocument.body.innerText = range.text;
                this.FrameTextArea.value = range.text;
            }
        }
    }
};

window.onload = function() {
    // 加载工具条 (start)
    var span = [8, 12, 16, 20, 25, 27, 30];
    var title = ["字体", "字号", "加粗", "倾斜", "下划线", "字体颜色",
        "背景颜色", "清除格式", "左对齐", "居中对齐", "右对齐", "取消对齐",
        "编号列表", "项目编号列表", "增加缩进", "减少缩进", "剪切", "复制",
        "粘贴", "删除对象", "创建链接", "取消链接", "图片", "视频", "小图标",
        "撤消", "恢复", "增加高度", "减少高度", "最大化切换", "编辑器模式",
        "使用帮助", "纯文本"];
    var a, s, divBar = Method.G(Common.ToolBar);
    for (var i = 1; i <= title.length; i++) {
        a = document.createElement("a");
        a.href = "javascript:;";
        a.className = Method.F("bar_{0}", i);
        a.onclick = new Function(Method.F("Do({0});", i));
        a.title = title[i - 1];
        divBar.appendChild(a);
        for (var ii = 0; ii < span.length; ii++) {
            if (i == span[ii]) {
                s = document.createElement("span");
                divBar.appendChild(s);
            }
        }
    }
    // 加载工具条 (end)

    var editor = Method.FD(Common.FrameName);
    Common.Doc.Div = new Editor_DivClass();
    Common.Doc.Editor = editor;
    Common.Doc.Tool = new Editor_OperationClass();

    editor.designMode = "on";
    //editor.contentEditable = true;
    //editor.open();
    //editor.body.innerHTML = _$._.Tool.ParentTextArea.value;
    //editor.close();
    //editor.charset="utf-8";
};

function Do(c) {
    var tool = Common.Doc.Tool;
    switch (c) {
        case 1: tool.Dialog("Family.htm"); break;
        case 2: tool.Dialog("FontSize.htm"); break;
        case 3: tool.Cmd("Bold"); break;
        case 4: tool.Cmd("Italic"); break;
        case 5: tool.Cmd("Underline"); break;
        case 6: tool.Dialog("Color.htm?Type=ForeColor"); break;
        case 7: tool.Dialog("Color.htm?Type=BackColor"); break;
        case 8: tool.Cmd("RemoveFormat"); break;
        case 9: tool.Cmd("JustifyLeft"); break;
        case 10: tool.Cmd("JustifyCenter"); break;
        case 11: tool.Cmd("JustifyRight"); break;
        case 12: tool.Cmd("JustifyNone"); break;
        case 13: tool.Cmd("InsertOrderedList"); break;
        case 14: tool.Cmd("InsertUnorderedList"); break;
        case 15: tool.Cmd("Indent"); break;
        case 16: tool.Cmd("Outdent"); break;
        case 17: tool.Cmd("Cut"); break;
        case 18: tool.Cmd("Copy"); break;
        case 19: tool.Cmd("Paste"); break;
        case 20: tool.Cmd("Delete"); break;
        case 21: tool.Dialog("Link.htm"); break;
        case 22: tool.Cmd("Unlink"); break;
        case 23: tool.Dialog("Image.htm"); break;
        case 24: tool.Dialog("Vedio.htm"); break;
        case 25: tool.Dialog("Face.htm"); break;
        case 26: tool.FrameDocument.execCommand("Undo"); break;
        case 27: tool.FrameDocument.execCommand("Redo"); break;
        case 28: tool.Height("+"); break;
        case 29: tool.Height("-"); break;
        case 30: tool.Size(); break;
        case 31: tool.ChangeMode(); break;
        case 32: tool.Dialog("Help.htm"); break;
        case 33: tool.Txt(); break;
    }
};


var r = "";
function xHTML(b) {

    var childs = b.childNodes;
    for (var i = 0; i < childs.length; i++) {
        if (childs[i].nodeType == 3) {
            r += childs[i].nodeValue + "\n";
        } else {
            r += "<" + childs[i].nodeName.toLowerCase();
            if (childs[i].attributes.length > 0) {
                for (var ii = 0; ii < childs[i].attributes.length; ii++) {
                    var specTags = /value|option|shape|coords/;
                    var attr = childs[i].attributes[ii]
                    if (attr.specified || attr.name.match(specTags)) {
                        if (attr.name == "style") {
                            r += " " + attr.name.toLowerCase() + "=";
                            r += "\"" + childs[i].style.cssText.toLowerCase() + "\"";
                        } else if (attr.value != "") {
                            r += " " + attr.name.toLowerCase() + "=";
                            r += "\"" + attr.value.toLowerCase() + "\"";
                        }
                    }
                }
            }
            var specNodes = /img|br|input|hr/;
            if (childs[i].nodeName.toLowerCase().match(specNodes)) {
                r += " />";
                xHTML(childs[i]);
            } else {
                r += ">";
                if (childs[i].nodeName == "SCRIPT") {
                    r += childs[i].innerHTML;
                } else {
                    if (childs[i].lastChild && childs[i].nodeType == 3) {
                        r += childs[i].lastChild.nodeValue;
                    }
                }
                xHTML(childs[i]);
                r += "</" + childs[i].nodeName.toLowerCase() + ">";
            }
            r += "\n";
        }
    }

    return r;
};